package com.atguigu.tingshu.order.handler;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.order.service.OrderInfoService;
import io.seata.common.util.StringUtils;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Package: com.atguigu.tingshu.order.handler
 *
 * @author xiongkunYang
 * @description:
 * @since 2025/6/26 17:13
 */
@Slf4j
//@Component
public class DelayMsgConsumer {


    private final RedissonClient redissonClient;

    private final OrderInfoService orderInfoService;

    public DelayMsgConsumer(RedissonClient redissonClient, OrderInfoService orderInfoService) {
        this.redissonClient = redissonClient;
        this.orderInfoService = orderInfoService;
    }

    /**
     * 项目启动后开启线程监听阻塞队列中消息
     */
    @PostConstruct
    public void cancelOrder() {
        log.info("开启线程监听延迟消息：");
        //1.创建阻塞队列（当队列内元素超过上限，继续队列发送消息，进入阻塞状态/当队列中元素为空，继续拉取消息，进入阻塞状态）
        RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue(MqConst.QUEUE_CANCEL_ORDER);
        //2.开启线程监听阻塞队列中消息 只需要单一核心线程线程池对象即可
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(()->{
            while (true) {
                String take;
                try {
                    take = blockingQueue.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (StringUtils.isNotBlank(take)) {
                    log.info("监听到延迟关单消息：{}", take);
                    // 查询订单状态，关闭订单
                    orderInfoService.cancelOrder(Long.valueOf(take));
                }
            }
        });
    }
}